package com.xjj.test.restful.controller;

import com.xjj.test.restful.entity.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 类描述:〈demo〉
 */
@RestController
@Validated
@RequestMapping("/user")
public class Controller1 {

  private List<User> users = new ArrayList<>();

  private Map<String, User> userMap = new HashMap<>();

  @RequestMapping(value = "/register", method = RequestMethod.POST)
  public String register(@Valid @RequestBody User user, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
      return bindingResult.getFieldError().getDefaultMessage();
    }
    if (userMap.containsKey(user.getUserName())) {
      return "用户名" + user.getUserName() + "已经存在";
    }
    users.add(user);
    userMap.put(user.getUserName(), user);
    return "注册用户成功";
  }


  @RequestMapping(value = "/search", method = RequestMethod.GET)
  public User getUser(@RequestParam String userName) {
    return userMap.get(userName);
  }


  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public List<User> getUsers() {
    return users;
  }


}
